// SMUserProfileViewController.m
#import "SMUserProfileViewController.h"
#import <Masonry/Masonry.h>
#import <SDWebImage/SDWebImage.h>

@interface SMUserProfileViewController ()
<UIPageViewControllerDataSource, UIPageViewControllerDelegate, UITableViewDelegate, UITableViewDataSource>

// 数据
@property(nonatomic, copy)   NSString *userId;

// 头部：渐变 + 资料卡
@property(nonatomic, strong) UIView *headerView;
@property(nonatomic, strong) CAGradientLayer *gradient;
@property(nonatomic, strong) UIView *card;
@property(nonatomic, strong) UIImageView *avatar;
@property(nonatomic, strong) UILabel *nameL, *bioL;
@property(nonatomic, strong) UIButton *followBtn, *msgBtn;

// Tabs（吸顶）
@property(nonatomic, strong) UIView *tabsBar;
@property(nonatomic, strong) UIStackView *tabs;
@property(nonatomic, strong) UIView *underline;
@property(nonatomic, assign) BOOL adjustingChildOffset; // 防止在 KVO 内部改 offset 引发重入

// 分页
@property(nonatomic, strong) UIPageViewController *pager;
@property(nonatomic, strong) NSArray<UIViewController*> *pages;
@property(nonatomic, assign) NSInteger currentIndex;

// 双锁联动
@property(nonatomic, weak)   UIScrollView *currentChildScroll;
@property(nonatomic, assign) CGFloat       headerHeight;     // tableHeaderView 高度（含安全区）
@property(nonatomic, assign) BOOL          canParentScroll;  // 父表能滚？
@property(nonatomic, assign) BOOL          canChildScroll;   // 子表能滚？

@end

@implementation SMUserProfileViewController

- (instancetype)initWithUserId:(NSString *)userId {
    if (self = [super initWithStyle:UITableViewStylePlain]) {
        _userId = [userId copy];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.backgroundColor = UIColor.systemGroupedBackgroundColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (@available(iOS 15.0, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    }

    [self buildHeaderView];
    [self buildTabsBar];
    [self buildPager];

    // 双锁初始：父能滚、子不能滚
    self.headerHeight    = CGRectGetHeight(self.headerView.frame);
    self.canParentScroll = YES;
    self.canChildScroll  = NO;

    // 整页刷新
    UIRefreshControl *rc = [UIRefreshControl new];
    [rc addTarget:self action:@selector(refreshAll) forControlEvents:UIControlEventValueChanged];
    self.refreshControl = rc;

    [self applyMockProfile];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    // 渐变覆盖 header 全部区域
    self.gradient.frame = self.headerView.bounds;
}

#pragma mark - Build UI

- (void)buildHeaderView {
    CGFloat safeTop = self.view.safeAreaInsets.top;
    CGFloat headerH = safeTop + 220;

    UIView *hv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, headerH)];
    hv.backgroundColor = UIColor.clearColor;
    self.headerView = hv;

    // 渐变
    CAGradientLayer *g = [CAGradientLayer layer];
    g.colors = @[
        (id)[UIColor colorWithRed:0.36 green:0.62 blue:0.98 alpha:1].CGColor,
        (id)[UIColor colorWithRed:0.75 green:0.87 blue:1 alpha:1].CGColor
    ];
    g.startPoint = CGPointMake(0, 0);
    g.endPoint   = CGPointMake(1, 1);
    g.frame = hv.bounds;
    [hv.layer insertSublayer:g atIndex:0];
    self.gradient = g;

    // 资料卡
    UIView *card = [UIView new];
    card.backgroundColor = UIColor.secondarySystemBackgroundColor;
    card.layer.cornerRadius = 16;
    card.layer.masksToBounds = YES;
    [hv addSubview:card];
    self.card = card;

    [card mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(hv.mas_top).offset(safeTop + 16);
        make.left.equalTo(hv).offset(16);
        make.right.equalTo(hv).offset(-16);
    }];

    // 头像 / 名称 / 签名 / 按钮（不重叠）
    self.avatar = [UIImageView new];
    self.avatar.layer.cornerRadius = 36; self.avatar.clipsToBounds = YES;
    [card addSubview:self.avatar];

    self.nameL = [UILabel new];
    self.nameL.font = [UIFont systemFontOfSize:18 weight:UIFontWeightSemibold];
    [card addSubview:self.nameL];

    self.bioL = [UILabel new];
    self.bioL.font = [UIFont systemFontOfSize:13];
    self.bioL.textColor = UIColor.secondaryLabelColor;
    self.bioL.numberOfLines = 2;
    [card addSubview:self.bioL];

    self.followBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    self.followBtn.layer.cornerRadius = 16;
    self.followBtn.contentEdgeInsets = UIEdgeInsetsMake(6, 14, 6, 14);
    [self.followBtn setTitle:@"关注" forState:UIControlStateNormal];
    [self.followBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    self.followBtn.backgroundColor = UIColor.systemBlueColor;
    [card addSubview:self.followBtn];

    self.msgBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    self.msgBtn.layer.cornerRadius = 16;
    self.msgBtn.contentEdgeInsets = UIEdgeInsetsMake(6, 14, 6, 14);
    [self.msgBtn setTitle:@"私信" forState:UIControlStateNormal];
    self.msgBtn.backgroundColor = [UIColor colorWithWhite:0.92 alpha:1];
    [card addSubview:self.msgBtn];

    [self.avatar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(card).offset(16);
        make.size.mas_equalTo(CGSizeMake(72, 72));
    }];
    [self.nameL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(card).offset(18);
        make.left.equalTo(self.avatar.mas_right).offset(12);
        make.right.lessThanOrEqualTo(card).offset(-16);
    }];
    [self.msgBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nameL.mas_bottom).offset(8);
        make.right.equalTo(card).offset(-16);
        make.height.mas_equalTo(32);
    }];
    [self.followBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.msgBtn);
        make.right.equalTo(self.msgBtn.mas_left).offset(-10);
        make.height.mas_equalTo(32);
    }];
    [self.bioL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nameL.mas_bottom).offset(8);
        make.left.equalTo(self.nameL);
        make.right.lessThanOrEqualTo(self.followBtn.mas_left).offset(-12);
    }];
    [card mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.avatar.mas_bottom).offset(16);
    }];

    self.tableView.tableHeaderView = hv;
}

- (void)buildTabsBar {
    UIView *bar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
    bar.backgroundColor = UIColor.systemBackgroundColor;
    self.tabsBar = bar;

    UIStackView *tabs = [[UIStackView alloc] init];
    tabs.axis = UILayoutConstraintAxisHorizontal;
    tabs.distribution = UIStackViewDistributionFillEqually;
    [bar addSubview:tabs];
    [tabs mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(bar);
        make.height.mas_equalTo(44);
    }];
    self.tabs = tabs;

    NSArray *titles = @[@"动态",@"出售",@"求购",@"收藏",@"关注",@"粉丝"];
    for (NSInteger i = 0; i < titles.count; i++) {
        UIButton *b = [UIButton buttonWithType:UIButtonTypeSystem];
        [b setTitle:titles[i] forState:UIControlStateNormal];
        b.tag = 100 + i;
        [b addTarget:self action:@selector(tapTab:) forControlEvents:UIControlEventTouchUpInside];
        [tabs addArrangedSubview:b];
    }

    UIView *under = [UIView new];
    under.backgroundColor = UIColor.labelColor;
    under.alpha = 0.25;
    [bar addSubview:under];
    [under mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(bar);
        make.height.mas_equalTo(2);
        make.width.equalTo(bar).multipliedBy(1.0/6.0);
        make.left.equalTo(bar.mas_left);
    }];
    self.underline = under;
}

- (void)buildPager {
    self.pager = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
                                               navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                                                             options:nil];

    UIViewController* (^mk1)(NSString*, NSString*, id) = ^UIViewController*(NSString *cls, NSString *selName, id arg){
        Class c = NSClassFromString(cls); if (!c) return [UIViewController new];
        SEL s = NSSelectorFromString(selName);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        id vc = [c alloc]; vc = [vc performSelector:s withObject:arg];
#pragma clang diagnostic pop
        return vc ?: [UIViewController new];
    };
    UIViewController* (^mk2)(NSString*, NSString*, id, id) = ^UIViewController*(NSString *cls, NSString *selName, id a, id b){
        Class c = NSClassFromString(cls); if (!c) return [UIViewController new];
        SEL s = NSSelectorFromString(selName);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        id vc = [c alloc]; vc = [vc performSelector:s withObject:a withObject:b];
#pragma clang diagnostic pop
        return vc ?: [UIViewController new];
    };

    UIViewController *vc0 = mk1(@"SMUserMomentsViewController", @"initWithUserId:", self.userId);
    UIViewController *vc1 = mk2(@"SMUserTradeListViewController", @"initWithUserId:type:", self.userId, @(0));
    UIViewController *vc2 = mk2(@"SMUserTradeListViewController", @"initWithUserId:type:", self.userId, @(1));
    UIViewController *vc3 = mk1(@"SMUserFavoritesViewController", @"initWithUserId:", self.userId);
    UIViewController *vc4 = mk2(@"SMUserFollowListViewController", @"initWithUserId:mode:", self.userId, @(0));
    UIViewController *vc5 = mk2(@"SMUserFollowListViewController", @"initWithUserId:mode:", self.userId, @(1));
    self.pages = @[vc0,vc1,vc2,vc3,vc4,vc5];
    self.currentIndex = 0;

    self.pager.dataSource = self;
    self.pager.delegate   = self;
    [self.pager setViewControllers:@[self.pages.firstObject]
                         direction:UIPageViewControllerNavigationDirectionForward
                          animated:NO
                        completion:nil];
}

#pragma mark - Table 数据源（1 section，1 行，header 为 tabsBar）

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; }
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 1; }

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { return self.tabsBar; }
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 44.0; }

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat h = self.view.bounds.size.height - 44.0; // 44 = tabsBar 高
    return MAX(h, 300);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)ip {
    static NSString *kId = @"pagerCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kId];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        // 内嵌 pager
        [self addChildViewController:self.pager];
        [cell.contentView addSubview:self.pager.view];
        [self.pager didMoveToParentViewController:self];

        self.pager.view.translatesAutoresizingMaskIntoConstraints = NO;
        [NSLayoutConstraint activateConstraints:@[
            [self.pager.view.topAnchor constraintEqualToAnchor:cell.contentView.topAnchor],
            [self.pager.view.leadingAnchor constraintEqualToAnchor:cell.contentView.leadingAnchor],
            [self.pager.view.trailingAnchor constraintEqualToAnchor:cell.contentView.trailingAnchor],
            [self.pager.view.bottomAnchor constraintEqualToAnchor:cell.contentView.bottomAnchor]
        ]];
    }
    // 绑定当前子页滚动
    [self attachChildScrollForIndex:self.currentIndex];
    return cell;
}

#pragma mark - Tab 切换

- (void)tapTab:(UIButton *)btn {
    NSInteger idx = btn.tag - 100;
    if (idx < 0 || idx >= self.pages.count || idx == self.currentIndex) return;

    UIPageViewControllerNavigationDirection dir =
    (idx > self.currentIndex) ? UIPageViewControllerNavigationDirectionForward : UIPageViewControllerNavigationDirectionReverse;
    self.currentIndex = idx;

    __weak typeof(self) weakSelf = self;
    [self.pager setViewControllers:@[self.pages[idx]] direction:dir animated:YES completion:^(BOOL finished) {
        [weakSelf updateUnderlineAnimated:YES];
        [weakSelf attachChildScrollForIndex:weakSelf.currentIndex];
    }];
}

- (void)updateUnderlineAnimated:(BOOL)animated {
    CGFloat w = self.tabsBar.bounds.size.width / 6.0;
    [self.underline mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.tabsBar.mas_left).offset(w * self.currentIndex);
    }];
    if (animated) {
        [UIView animateWithDuration:0.25 animations:^{ [self.tabsBar layoutIfNeeded]; }];
    } else {
        [self.tabsBar layoutIfNeeded];
    }
}

#pragma mark - Page 代理

- (UIViewController *)pageViewController:(UIPageViewController *)p viewControllerBeforeViewController:(UIViewController *)vc {
    NSInteger i = [self.pages indexOfObject:vc];
    if (i == NSNotFound || i == 0) return nil;
    return self.pages[i - 1];
}

- (UIViewController *)pageViewController:(UIPageViewController *)p viewControllerAfterViewController:(UIViewController *)vc {
    NSInteger i = [self.pages indexOfObject:vc];
    if (i == NSNotFound || i >= self.pages.count - 1) return nil;
    return self.pages[i + 1];
}

- (void)pageViewController:(UIPageViewController *)p didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {
    if (!completed) return;
    NSInteger i = [self.pages indexOfObject:p.viewControllers.firstObject];
    if (i == NSNotFound) return;
    self.currentIndex = i;
    [self updateUnderlineAnimated:YES];
    [self attachChildScrollForIndex:self.currentIndex];
}

#pragma mark - 双锁联动

- (void)attachChildScrollForIndex:(NSInteger)index {
    if (index < 0 || index >= self.pages.count) return;
    UIScrollView *s = [self findFirstScrollIn:self.pages[index].view];

    // 解绑旧观察
    @try { [self.currentChildScroll removeObserver:self forKeyPath:@"contentOffset"]; } @catch (__unused NSException *e) {}

    self.currentChildScroll = s;
    if (!s) return;

    // 避免额外 inset 干扰
    s.contentInset = UIEdgeInsetsZero;
    s.scrollIndicatorInsets = UIEdgeInsetsZero;
    if (@available(iOS 11.0, *)) s.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;

    s.contentOffset = CGPointZero;

    // 观察子表 offset，用于“子回到顶 -> 切回父滚”
    [s addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:NULL];
}

- (UIScrollView *)findFirstScrollIn:(UIView *)v {
    if ([v isKindOfClass:UIScrollView.class]) return (UIScrollView *)v;
    for (UIView *sub in v.subviews) {
        UIScrollView *res = [self findFirstScrollIn:sub];
        if (res) return res;
    }
    return nil;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView != self.tableView) return;

    CGFloat y   = scrollView.contentOffset.y;
    CGFloat cap = self.headerHeight;  // 折叠阈值：header 完全滚走

    if (!self.canParentScroll) {
        // 父被锁：钉在阈值，避免抖动
        [scrollView setContentOffset:CGPointMake(0, cap) animated:NO];
        return;
    }
    

    if (y >= cap) {
        // 父滚到头：锁父，放子
        [scrollView setContentOffset:CGPointMake(0, cap) animated:NO];
        self.canParentScroll = NO;
        self.canChildScroll  = YES;
        self.currentChildScroll.showsVerticalScrollIndicator = YES;
    } else {
        // 父阶段：禁用子滚，停在顶
        self.canChildScroll = NO;
        if (self.currentChildScroll) {
            if (!CGPointEqualToPoint(self.currentChildScroll.contentOffset, CGPointZero)) {
                self.adjustingChildOffset = YES;
                [self.currentChildScroll setContentOffset:CGPointZero animated:NO];
                self.adjustingChildOffset = NO;
            }
            self.currentChildScroll.showsVerticalScrollIndicator = NO;
        }
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                       context:(void *)context {
    if (![keyPath isEqualToString:@"contentOffset"]) return;
    if (object != self.currentChildScroll) return;
    if (!self.currentChildScroll) return;                 // 防护：已切页或释放
    if (self.adjustingChildOffset) return;                // 防护：避免重入

    // 不允许子滚动时，强行把子停在顶部（但只有在确实不是 0 的时候才改，避免重复触发）
    if (!self.canChildScroll) {
        if (!CGPointEqualToPoint(self.currentChildScroll.contentOffset, CGPointZero)) {
            self.adjustingChildOffset = YES;
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.currentChildScroll) {
                    [self.currentChildScroll setContentOffset:CGPointZero animated:NO];
                }
                self.adjustingChildOffset = NO;
            });
        }
        return;
    }

    // 子页在滚：当回到顶继续下拉时，切回父滚
    if (self.currentChildScroll.contentOffset.y <= 0.0) {
        self.canChildScroll  = NO;
        self.canParentScroll = YES;
    }
}


- (void)dealloc {
    @try { [self.currentChildScroll removeObserver:self forKeyPath:@"contentOffset"]; } @catch (__unused NSException *e) {}
}

#pragma mark - Refresh & Mock

- (void)refreshAll {
    // 这里可以转发给当前子页刷新
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.refreshControl endRefreshing];
    });
}

- (void)applyMockProfile {
    NSString *av = [NSString stringWithFormat:@"https://i.pravatar.cc/150?u=%@", self.userId ?: @"guest"];
    UIImage *ph = nil; if (@available(iOS 13.0, *)) ph = [UIImage systemImageNamed:@"person.crop.circle.fill"];
    [self.avatar sd_setImageWithURL:[NSURL URLWithString:av] placeholderImage:ph];
    self.nameL.text = @"废钢圈-用户";
    self.bioL.text  = @"专注重废/剪切料，长期合作，欢迎同行交流。";
}

@end
